





from collections import Counter
from sklearn.feature_selection import RFECV
from sklearn.model_selection import StratifiedKFold
import numpy as np
import pandas as pd
import sys
import os





# 将项目根目录添加到 Python 的模块搜索路径
sys.path.append(os.path.abspath('../../'))  # 替换为项目根目录

# 现在可以正常导入模块
from ModelDefination.CARTDT.CARTDecisionTree import CARTDecisionTree





from sklearn.feature_selection import SelectKBest, f_classif

train_data = pd.read_csv('../../RefreshedData/refreshed_train.csv')
test_data = pd.read_csv('../../RefreshedData/refreshed_test.csv')

X = train_data.iloc[:, :-1]
y = train_data.iloc[:, -1]

selector = SelectKBest(f_classif, k=10)  # 选前10个最相关特征
X_new = selector.fit_transform(X, y)
# 查看哪些特征被选中了
mask = selector.get_support() 
selected_features = X.columns[mask]
train_selected_data = list(mask)
test_selected_data = list(mask)
train_selected_data.append(True)
selected_train = train_data.iloc[:, train_selected_data]
selected_test = test_data.iloc[:, test_selected_data]

# 将特征选择后的文件输出
selected_train.to_csv('../../FeatureSelectedData/Cart/cart_train.csv', index=False)
selected_test.to_csv('../../FeatureSelectedData/Cart/cart_test.csv', index=False)

print("Selected features:", selected_features)





from joblib import dump, load

final_train_data = pd.read_csv('../../FeatureSelectedData/Cart/cart_train.csv')
final_X_train = final_train_data.iloc[:, :-1].values
final_y_train = final_train_data.iloc[:, -1].values


clf = CARTDecisionTree(max_depth=10)

clf.fit(final_X_train, final_y_train)


dump(clf, '../../ModelFile/Cart/cart_model.joblib')
print("Model saved as svm_model.joblib")





def Cart(X):
    clf = load('../../ModelFile/Cart/cart_model.joblib')
    y_predicted = clf.predict(test_data)
    return y_predicted





final_test_data = pd.read_csv('../../FeatureSelectedData/Cart/cart_test.csv')
result_file = pd.read_csv('../../RawData/sample_submission.csv')
predictions = Cart(final_test_data)
result_file["Transported"] = pd.Series(predictions, result_file.index)
result_file.to_csv('../../predictions/Cart/cart_svm.csv', index=False)



